package com.budwk.app.sqfwV2.service.impl;

import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.models.SqfwProblemFeed;
import com.budwk.app.sqfw.vo.SqfwProblemFeedVO;
import com.budwk.app.sqfwV2.service.ProblemFeedService;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.time.LocalDateTime;

@Slf4j
@IocBean(args = {"refer:dao"})
public class ProblemFeedServiceImpl extends BaseServiceImpl<SqfwProblemFeed> implements ProblemFeedService {
    public ProblemFeedServiceImpl(Dao dao) {
        super(dao);
    }

    @Override
    public SqfwProblemFeed submitData(SqfwProblemFeed problemFeed) {
        problemFeed.setCreateDate(LocalDateTime.now())
                .setCreateId(SecurityUtil.getUserId())
                .setUpdateDate(LocalDateTime.now())
                .setUpdateId(SecurityUtil.getUserId())
                .setDeleted(false)
                .setReaded(false);
        this.insert(problemFeed);
        return problemFeed;
    }

    @Override
    public Pagination page(SqfwProblemFeedVO bean) {
        Criteria criteria = buildQueryCond(bean);
        log.info("ProblemFeedServiceImpl-list-SQL: {}", criteria.toString());
        Pagination pagination = this.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
        return pagination;
    }

    private Criteria buildQueryCond(SqfwProblemFeedVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();

        // 组装查询条件
        if (StringUtils.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            if (bean.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(bean.getPageOrderName());
            }
            if (bean.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(bean.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(SqfwProblemFeed::getCreateDate);
        }

        // 姓名
        if (StringUtils.isNotBlank(bean.getOperater())) {
            criSql.andLike(SqfwProblemFeed::getOperater, bean.getOperater());
        }
        // 电话号码
        if (StringUtils.isNotBlank(bean.getOperaterMobile())) {
            criSql.andLike(SqfwProblemFeed::getOperaterMobile, bean.getOperaterMobile());
        }
        return cri;
    }
}
